package com.t.testsql;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class sqlDao {

    private static Sqldatabase msqldatabase;

    private static sqlDao msqlDao;


    private sqlDao() {
        if (msqldatabase == null) {
            msqldatabase = new Sqldatabase(App.mcontext);
        }
    }

    public static sqlDao getInstance() {
        synchronized (sqlDao.class) {
            if (msqlDao == null) {
                msqlDao = new sqlDao();
            }
            return msqlDao;
        }
    }


    protected void insert(DataEntity.DataBean bean) {
        SQLiteDatabase database = msqldatabase.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(Sqldatabase.COULUMN_NAME, bean.getName());
        values.put(Sqldatabase.COULUMN_AGE, bean.getAge());
        values.put(Sqldatabase.COULUMN_PHONE, bean.getPhone());
        // 使用安卓原生的api，能够判断是否插入成功。
        long insert = database.insert(Sqldatabase.TABLE_NAME, null, values);
        if (insert != -1) {
            Log.e("sqlDao", "insert success");
        }
    }

    protected void update(String traget, String origin) {
        SQLiteDatabase database = msqldatabase.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",traget);
        database.update(Sqldatabase.TABLE_NAME, values, "name=?", new String[]{origin});
    }

    protected void query () {
        SQLiteDatabase database = msqldatabase.getWritableDatabase();
        Cursor cursor = database.query(Sqldatabase.TABLE_NAME, null
                , null, null, null, null, null);
        if (cursor !=null ) {
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex((Sqldatabase.COULUMN_NAME)));
                Log.e("sqlDao", "query :" + name);
            }
        }
    }

    // 单独查询某个语句
    protected void query1 (String name) {
        SQLiteDatabase database = msqldatabase.getWritableDatabase();
        // 记住如果用到了 selectionarg 那么，前面的selection 后面是 =?
        Cursor cursor = database.query(Sqldatabase.TABLE_NAME, null
                , "name =?", new String[]{name}, null, null, null);
        if (cursor !=null ) {
            while (cursor.moveToNext()) {
                String phone = cursor.getString(cursor.getColumnIndex((Sqldatabase.COULUMN_PHONE)));
                Log.e("sqlDao", "query :" + phone);
            }
        }
    }
}
